package com.qf.springbootproject.order.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.springbootproject.index.entity.Product;
import com.qf.springbootproject.index.service.ProductService;
import com.qf.springbootproject.order.entity.OrderItem;
import com.qf.springbootproject.order.entity.Orders;
import com.qf.springbootproject.order.mapper.OrdersMapper;
import com.qf.springbootproject.order.service.OrderItemService;
import com.qf.springbootproject.order.service.OrdersService;
import com.qf.springbootproject.product.entity.ProductSku;
import com.qf.springbootproject.product.service.ProductSkuService;
import com.qf.springbootproject.shopcart.entity.ShoppingCart;
import com.qf.springbootproject.shopcart.service.ShoppingCartService;
import com.qf.springbootproject.wechat.WxpayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单  服务实现类
 * </p>
 *
 * @author weq
 * @since 2023-02-17
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    ProductSkuService productSkuService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    ProductService productService;
    @Autowired
    OrderItemService orderItemService;

    /**
     * 下单接口
     *
     * @param cids
     * @param orders
     * @return
     */
    @Override
    public Map<String, Object> add(Integer[] cids, Orders orders) throws Exception {
        //1.查询用户购物车中的对应的商品套餐库存量是否足够
        //如果库存够，则继续下单流程；如果库存量不足。直接抛异常
        List<ShoppingCart> skuList = shoppingCartService.list(new QueryWrapper<ShoppingCart>().in("cart_id", cids));
        List<String> skuId = skuList.stream().map(shoppingCart -> shoppingCart.getSkuId()).collect(Collectors.toList());
        List<ProductSku> productSkuList = productSkuService.list(new QueryWrapper<ProductSku>().in("sku_id", skuId));
        for (ShoppingCart shoppingCart : skuList) {
            Integer catNum = Integer.parseInt(shoppingCart.getCartNum());
            for (ProductSku productSku : productSkuList) {
                Integer stock = productSku.getStock();
                if (catNum > stock) {
                    throw new Exception();
                }
            }
        }
        //2.生成唯一的订单编号 uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //3.生成订单主表（order表）中的数据
        Orders orders1 = new Orders();
        orders1.setOrderId(uuid + "");
        orders1.setUserId(orders.getUserId());
        String str = "";
        for (int i = 0; i < productSkuList.size(); i++) {
            ProductSku productSku = productSkuList.get(i);
            if (i == productSkuList.size() - 1) {
                str = str + productSku.getSkuName();
            } else {
                str = str + productSku.getSkuName() + ",";
            }
        }

        //int index = str.lastIndexOf(",");
        //str.substring(0,index);
        orders1.setUntitled(str);
        orders1.setReceiverName(orders.getReceiverName());
        orders1.setReceiverMobile(orders.getReceiverMobile());
        orders1.setReceiverAddress(orders.getReceiverAddress());
        orders1.setTotalAmount(orders.getTotalAmount());
        orders1.setActualAmount(orders.getActualAmount());
        orders1.setPayType(orders.getPayType());
        orders1.setOrderRemark(orders.getOrderRemark());
        orders1.setCreateTime(LocalDateTime.now());
        orders1.setStatus("1");
        save(orders1);
        //4.生成订单明细表(order_item)
        //购物车有几条数据，订单明细表就有几条数据
        String productName = null;
        for (ShoppingCart shoppingCart : skuList) {
            OrderItem orderItem = new OrderItem();
            String uuid1 = UUID.randomUUID().toString().replace("-", "");
            orderItem.setItemId(uuid1 + "");
            orderItem.setOrderId(uuid + "");
            orderItem.setProductId(shoppingCart.getProductId());
            Product product = productService.getOne(new QueryWrapper<Product>().eq("product_id", shoppingCart.getProductId()));
            productName = product.getProductName();
            orderItem.setProductName(productName);
            orderItemService.save(orderItem);
        }
        //5.删除用户购物车中的cids对应数据
        shoppingCartService.remove(new QueryWrapper<ShoppingCart>().in("cart_id", cids));
        //6.跟微信支付平台交互，获取可以支付的url
        String code_url = WxpayUtils.getPayUrl(uuid + "");
        //7.返回map数据
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", uuid);
        map.put("productNames", productName);
        map.put("payUrl", code_url);
        return map;
    }
}















